package com.san.metadata.controller;

import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.san.base.controller.BaseController;
import com.san.common.annotation.Log;
import com.san.common.utils.Constant;
import com.san.common.utils.ExcelUtil;
import com.san.common.utils.FileUtil;
import com.san.common.utils.Query;
import com.san.common.utils.R;
import com.san.metadata.domain.DataImportDTO;
import com.san.metadata.domain.TechnicalColumnsDO;
import com.san.metadata.domain.TechnicalTableDO;
import com.san.metadata.service.DataImportService;
import com.san.metadata.service.TechnicalMetadataService;
import com.san.metadata.task.DataImportThread;

/**
 * 数据导入业务控制类
 */
@Controller
@RequestMapping("/md/dataImport")
public class DataImportController extends BaseController {

	/**
	 * 本功能地址前缀
	 */
	private static final String PREFIX = "metadata/dataImport";

	@Autowired
	private TechnicalMetadataService technicalService;

	@Autowired
	private DataImportService dataImportService;

	@GetMapping("")
	@Log("访问数据导入主界面")
	@RequiresPermissions("md:dataImport:view")
	String view() {
		return PREFIX + "/view";
	}

	@PostMapping("/getTechnicalImportTable")
	@ResponseBody
	public List<TechnicalTableDO> getTechnicalImportTable(@RequestParam Map<String, Object> params) {
		params.put("importType", Constant.IMPORT_TYPE_HAND);
		params.put("createFlag", Constant.CREATE_FLAG_YES);
		List<TechnicalTableDO> result = null;
		try {
			result = technicalService.allTechnicalTable(new Query(params));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	@GetMapping("/download/{tableId}")
	public ResponseEntity<byte[]> downLoad(Model model, @PathVariable("tableId") Long tableId) throws Exception {
		TechnicalTableDO technicalTableDO = technicalService.getById(tableId);
		List<TechnicalColumnsDO> list = technicalService.allTechnicalColumns(tableId);
		XSSFWorkbook workbook = new XSSFWorkbook();
		XSSFSheet sheet = workbook.createSheet();

		// 创建第一行
		XSSFRow row = sheet.createRow(0);
		XSSFCell cell = null;
		int cellNum = 0;
		for (TechnicalColumnsDO technicalColumnsDO : list) {
			//入库时间字段不在导入文件中体现，后台自动生成
			if (Constant.NDATA_IMPORT_AUTO_INPUT_DATE.equals(technicalColumnsDO.getColumnName())) {
				continue;
			}
			cell = row.createCell(cellNum);
			// 设置单元格值
			ExcelUtil.setValue(cell, technicalColumnsDO.getColumnComment().toUpperCase());
			// 设置单元格宽度
			ExcelUtil.setWidth(sheet, cell);
			cellNum++;
		}

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		workbook.write(os);
		byte[] bytes = os.toByteArray();
		workbook.close();
		return FileUtil.xlsxExport(bytes, technicalTableDO.getTargetTableComment());

	}

	/**
	 * 导入
	 */
	@RequiresPermissions("md:dataImport:doImport")
	@Log("数据导入")
	@PostMapping("/doImport")
	@ResponseBody
	public R doImport(DataImportDTO dataImportDTO) {
		try {
			dataImportDTO.setUserId(getUserId());
			Date date = new Date();
			dataImportDTO.setBatchNo("9" + date.getTime());
			DataImportThread thread = new DataImportThread(dataImportService, dataImportDTO);
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.ok("数据导入已转入后台处理，稍后请在我的通知中查看导入结果，导入批次号为：" + dataImportDTO.getBatchNo());
	}

}
